<template>
  <div class="drawer-wrapper">
    <el-button type="primary" @click="openDrawer" :loading="isSubmitting" class="open-drawer-btn">
      手动添加
    </el-button>
    <el-drawer
      v-model="drawerVisible"
      title="手动添加新闻"
      direction="rtl"
      size="50%"
      :before-close="handleBeforeClose"
      class="news-drawer"
      :destroy-on-close="true"
    >
      <el-form ref="formRef" :model="newsForm" label-width="90px" class="news-form">
        <div class="form-layout">
          <div class="form-left">
            <el-form-item label="新闻标题" class="form-item" prop="newsTitle">
              <el-input
                v-model="newsForm.newsTitle"
                placeholder="请输入新闻标题"
                :maxlength="100"
                show-word-limit
                clearable
              ></el-input>
            </el-form-item>

            <el-form-item label="新闻标签" class="form-item" prop="tags">
              <el-select
                v-model="newsForm.tags"
                placeholder="请选择新闻标签"
                clearable
                filterable
                allow-create
                default-first-option
              >
                <el-option
                  v-for="tag in availableTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="新闻来源" class="form-item">
              <el-input v-model="newsForm.source" placeholder="请输入新闻来源" clearable></el-input>
            </el-form-item>

            <el-form-item label="新闻网址" class="form-item">
              <el-input
                v-model="newsForm.url"
                type="url"
                placeholder="请输入新闻网址"
                clearable
              ></el-input>
            </el-form-item>

            <el-form-item label="新闻摘要" class="form-item" prop="summary">
              <el-input
                v-model="newsForm.summary"
                type="textarea"
                :rows="5"
                placeholder="请输入新闻摘要"
                :maxlength="500"
                show-word-limit
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="新闻内容" class="form-item" prop="content">
              <el-input
                v-model="newsForm.content"
                type="textarea"
                :rows="5"
                placeholder="请输入新闻内容"
                :maxlength="500"
                show-word-limit
                clearable
              ></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="isSubmitting" @click="handleSubmit">确定</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { categoryList } from './category'
import { insertNews } from '@/API/AllApi'

const availableTags = categoryList.map((tag) => tag.label)

const emit = defineEmits(['newsAdded', 'close'])

const drawerVisible = ref(false)
const isSubmitting = ref(false)
const formRef = ref(null)

const newsForm = reactive({
  id: null,
  newsTitle: '',
  tags: '',
  classReal: 0,
  source: '',
  url: '',
  summary: '',
  content: '',
})


const openDrawer = () => {
  resetForm()
  drawerVisible.value = true
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(newsForm, {
    id: null,
    newsTitle: '',
    tags: '',
    source: '',
    url: '',
    summary: '',
    content: '',
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    isSubmitting.value = true
    const submitData = {
      id: newsForm.id,
      newsTitle: newsForm.newsTitle,
      abstractReal: newsForm.summary,
      newsSource: newsForm.source,
      sourceUrl: newsForm.url,
      classModel: newsForm.tags,
      newsContent: newsForm.content,
      classReal: categoryList.find((tag) => tag.label === newsForm.tags)?.value || 0,
      addMode: 1,
    }

    console.log('提交到接口的数据:', submitData)

    const response = await insertNews(submitData)

    if (response.code === 200 || response.success) {
      ElMessage.success('新闻添加成功')
      drawerVisible.value = false
      resetForm()

      emit('newsAdded')
    } else {
      ElMessage.error(response.message || '新闻添加失败，请稍后重试')
    }
  } catch (error) {
    if (error === false) {
      ElMessage.warning('请填写必填项')
    } else {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    }
  } finally {
    isSubmitting.value = false
  }
}

const handleCancel = () => {
  resetForm()
  drawerVisible.value = false
  emit('close')
}

const handleBeforeClose = (done) => {
  resetForm()
  done()
  emit('close')
}

defineExpose({
  openDrawer,
  handleCancel,
})
</script>

<style scoped>
.drawer-wrapper {
  position: relative;
}

.open-drawer-btn {
  margin-bottom: 16px;
}

.news-drawer {
  padding: 20px;
}

.news-form {
  max-width: 100%;
}

.form-left {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  display: block;
  margin-bottom: 8px;
  text-align: left;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner),
:deep(.el-select__wrapper) {
  border-radius: 4px;
  width: 100%;
}

:deep(.el-drawer__header) {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

:deep(.el-drawer__title) {
  font-size: 18px;
  font-weight: 600;
}
</style>
